package com.atguigu.dev;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class ShareResource {
    private int num = 1;
    Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();


    public void printNum() throws InterruptedException {

        lock.lock();
        try {
            for (int i = 1; i <= 52; i++) {
                //1、判断
                while (num % 3 == 0) {
                    condition.await();
                }

                //2、干活
                System.out.println(Thread.currentThread().getName() + "\t" + i);
                num++;
                //3、通知
                condition.signal();

            }
        } finally {
            lock.unlock();
        }


    }

    public void printChara() throws InterruptedException {

        lock.lock();

        try {
            for (char i = 'A'; i < 'Z'; i++) {
                //打印字母的方法

                while (num % 3 != 0) {
                    try {
                        condition.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                System.out.println(Thread.currentThread().getName() + "\t" + i);
                //改条件,唤醒下一个线程
                num++;

                condition.signal();

            }
        } finally {
            lock.unlock();
        }
    }

}


public class InterviewTest1 {
    /*两个线程，一个线程打印1-52，另一个打印字母A-Z
    打印顺序为12A34B...5152Z,要求用线程间通信*/
    public static void main(String[] args) {

        ShareResource shareResource = new ShareResource();
        new Thread(() -> {
            try {
                shareResource.printNum();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }, "T1").start();


        new Thread(() -> {
            try {
                shareResource.printChara();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }, "T2").start();
    }
}
